package com.ihr360.feign.errordecoder;

import com.alibaba.fastjson.JSONObject;
import com.ihr360.commons.exception.Ihr360Exception;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Eric on 2018/5/18/018.
 */
public class FeignErrorDecoder implements ErrorDecoder {
    private Logger logger = LoggerFactory.getLogger(FeignErrorDecoder.class);

    private static final String ERROR_MESSAGE = "errorMsg";
    private static final String MESSAGE = "message";

    public Exception decode(String s, Response response) {
        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader());
                logger.error(body);
                JSONObject res = JSONObject.parseObject(body);
                if (res.containsKey(MESSAGE) || res.containsKey(ERROR_MESSAGE)) {
                    String message = res.get(ERROR_MESSAGE) == null ? res.get(MESSAGE).toString() : res.get(ERROR_MESSAGE).toString();
                    return new Ihr360Exception(null, message);
                } else {
                    return new Ihr360Exception(null, "系统异常，请联系管理员");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new Ihr360Exception(null, "系统异常，请联系管理员");
        }
        return new Ihr360Exception(null, "系统异常，请联系管理员");
    }
}
